(function($) {
	var div = $('<div/>'), ajax = epic.ajax, flash = epic.flash, 
	say = epic.say, servers = epic.servers;


	// stores the created user in a cookie
	function storeUser(data) {
		var xmpp = servers.xmpp();
		cookie.set('id', $('id',data).text());
		cookie.set('jid', $('name',data).text()+"@"+xmpp.domain);
		cookie.set('pw',$('name',data).text());
		cookie.set('url',xmpp.url);
	}

	// registeres the user with the epic web service
	function register(params) {
		say('register at: ' + url);
		ajax(jQuery.extend({},  {
			url: url + '/users.xml',
			type: 'POST',
			data: 'something=forwebos'
		}, params));
	}


	// unregisteres the user with the epic web service
	function unregister(params){
		var id = cookie.get().id;
		say('unregister ' + id + ' at: ' + url);
		if(id) {
			ajax($.extend({
				url: url + '/users/' + id,
				type: 'POST',
				data: '_method=delete'
			}, params));
		}
	}


	// updates the url, and checks if server is alive
	function updateURL() {
		url = servers.details[servers.model.value].url;
		say('updateServerUrl: ' + url);
		flash('info', 'checking for ' + url);
		ajax({
			url: url + "/users.xml",
			success: function(data,status,xhr) {
				if(xhr.status === 0) {
					flash('error', 'no response');
				} else {
					flash('info', 'success');
				}
			}
		});
	}

	// public api methods
	epic.api = {
		register: register,
		unregister: unregister,
		updateURL: updateURL,
		storeUser: storeUser

	};

})(jQuery);
